import React, { useEffect } from 'react'
import styles from './App.module.css'
import {
  BrowserRouter,
  Navigate,
  Route,
  Routes,
  useNavigate,
  useRoutes,
} from 'react-router-dom'
import { HomePage } from './pages'
import {
  SignInPage,
  RegisterPage,
  DetailsPage,
  SearchPage,
  ShoppingCartPage,
  PlaceOrderPage,
} from './pages'
import { NotFound } from './NotFound'

import { AuthRouter } from './router/authRouter'

import { useDispatch, useSelector } from 'react-redux'
import { getShoppingCart } from './redux/shoppingCart/slice'

// 1. 准备一个路由数组 数组中定义所有的路由对应关系
const routesList = [
  {
    path: '/',
    element: <HomePage />,
  },
  {
    path: '/login',
    element: <SignInPage />,
  },
  {
    path: '/register',
    element: <RegisterPage />,
  },
  {
    path: '/details/:touristRouteId',
    element: <DetailsPage />,
  },
  {
    path: '/search/:keywords?',
    element: <SearchPage />,
  },
  {
    path: '/shoppingCart',
    element: (
      <AuthRouter>
        <ShoppingCartPage />
      </AuthRouter>
    ),
  },
  {
    path: '/placeOrder',
    element: (
      <AuthRouter>
        <PlaceOrderPage />
      </AuthRouter>
    ),
  },

  // 增加n个路由对应关系
  {
    path: '*',
    element: <NotFound />,
  },
]

// 2. 使用useRoutes方法传入routesList生成Routes组件
function WrapperRoutes() {
  let element = useRoutes(routesList)
  return element
}

function App() {
  const token = useSelector((state: any) => state.user.token)
  const dispatch = useDispatch()
  useEffect(() => {
    if (token) {
      dispatch(getShoppingCart(token))
    }
  }, [token])

  return (
    <div className={styles.App}>
      <BrowserRouter>
        <WrapperRoutes />
      </BrowserRouter>
    </div>
  )
}
export default App
